import axios from 'axios'

const instance = axios.create({
  baseURL: '/api'
})
import { Message } from 'element-ui'
// import { getToken } from './auth'
import { getTimeStamp } from './auth';
import store from '@/store';
import router from '@/router'


// 拦截器
// 请求拦截
const time = 300 * 60 * 1000
// const time = 6 * 1000

instance.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      const timeStamp = Date.now()
      // 判断token的时间戳是否超时
      if (timeStamp - getTimeStamp() >= time) {
        Message.info('登录信息过期，请重新登录')
        store.dispatch('user/logout')
        router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
        return
      }
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
instance.interceptors.response.use(
  response => {
    const {
      data: { success, message }
    } = response
    // console.log(data)
    if (success) {
      return response.data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // console.dir(error)
    // code是10002则是token过期，退出登录，返回登录页
    if (error.response && error.response.data && error.response.data.code === 10002) {
      Message.info('登录信息过期，请重新登录')
      store.dispatch('user/logout')
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
    }
    return Promise.reject(error)
  }
)

export default instance
